package udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.io.IOException;


public class Receive {
    private static final int BUFFER_SIZE = 1024;
    private static final int PORT = 9999;

    public static void main(String[] args) {
        try (DatagramSocket ds = new DatagramSocket(PORT)) {
            byte[] buf = new byte[BUFFER_SIZE];
            DatagramPacket dp = new DatagramPacket(buf, buf.length);

            ds.receive(dp);

            handleReceivedData(dp);
        } catch (IOException e) {
            // 更细致的异常处理，输出更多上下文信息
            e.printStackTrace();
        }
    }

    private static void handleReceivedData(DatagramPacket dp) {
        byte[] data = dp.getData();
        InetAddress inetAddress = dp.getAddress();
        int port = dp.getPort();
        int length = dp.getLength();

        String str = new String(data, 0, length);
        // 使用日志记录接收到的数据，而不是直接使用System.out.println
        System.out.println("ip:" + inetAddress.getHostAddress());
        System.out.println("port:" + port);
        System.out.println("data:" + str);
    }
}
